// 简单的五子棋AI实现
import DataBus from '../databus'

export default class GameAI {
  constructor() {
    this.databus = new DataBus()
    this.size = 15 // 15x15棋盘
    this.difficulty = 'medium'
  }

  /**
   * 设置AI难度
   */
  setDifficulty(difficulty) {
    this.difficulty = difficulty
  }

  /**
   * 获取AI的下一步落子位置
   */
  getNextMove(board, player) {
    const depth = this.getSearchDepth()
    const result = this.search(board, depth, player)
    
    if (result && result.point) {
      return {
        row: result.point[0],
        col: result.point[1]
      }
    }
    
    // 如果没有找到最佳走法，返回一个随机空位
    return this.getRandomMove(board)
  }

  /**
   * 根据难度获取搜索深度
   */
  getSearchDepth() {
    switch (this.difficulty) {
      case 'easy': return 2
      case 'medium': return 3
      case 'hard': return 4
      default: return 3
    }
  }

  // 简单的评估函数
  evaluate(board, role) {
    let score = 0
    const directions = [[1, 0], [0, 1], [1, 1], [1, -1]]
    
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < this.size; j++) {
        if (board[i][j] === 0) continue
        
        for (const [di, dj] of directions) {
          let count = 1
          let blocked = 0
          
          // 向一个方向数
          let ni = i + di
          let nj = j + dj
          while (ni >= 0 && ni < this.size && nj >= 0 && nj < this.size && board[ni][nj] === board[i][j]) {
            count++
            ni += di
            nj += dj
          }
          if (ni < 0 || ni >= this.size || nj < 0 || nj >= this.size || board[ni][nj] !== 0) {
            blocked++
          }
          
          // 向相反方向数
          ni = i - di
          nj = j - dj
          while (ni >= 0 && ni < this.size && nj >= 0 && nj < this.size && board[ni][nj] === board[i][j]) {
            count++
            ni -= di
            nj -= dj
          }
          if (ni < 0 || ni >= this.size || nj < 0 || nj >= this.size || board[ni][nj] !== 0) {
            blocked++
          }
          
          // 计算分数
          let pieceScore = this.getPieceScore(count, blocked)
          if (board[i][j] === role) {
            score += pieceScore
          } else {
            score -= pieceScore
          }
        }
      }
    }
    
    return score
  }

  getPieceScore(count, blocked) {
    if (count >= 5) return 100000
    if (count === 4 && blocked === 0) return 10000
    if (count === 4 && blocked === 1) return 1000
    if (count === 3 && blocked === 0) return 1000
    if (count === 3 && blocked === 1) return 100
    if (count === 2 && blocked === 0) return 100
    if (count === 2 && blocked === 1) return 10
    return count
  }

  // 获取有价值的移动位置
  getValuableMoves(board, role) {
    const moves = []
    const visited = Array(this.size).fill().map(() => Array(this.size).fill(false))
    
    // 找到所有已有棋子周围的空位
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < this.size; j++) {
        if (board[i][j] !== 0) {
          // 检查周围8个方向
          for (let di = -1; di <= 1; di++) {
            for (let dj = -1; dj <= 1; dj++) {
              if (di === 0 && dj === 0) continue
              
              let ni = i + di
              let nj = j + dj
              if (ni >= 0 && ni < this.size && nj >= 0 && nj < this.size && 
                  board[ni][nj] === 0 && !visited[ni][nj]) {
                moves.push([ni, nj])
                visited[ni][nj] = true
              }
            }
          }
        }
      }
    }
    
    // 如果棋盘为空，返回中心位置
    if (moves.length === 0) {
      const center = Math.floor(this.size / 2)
      moves.push([center, center])
    }
    
    return moves
  }

  // 极小化极大算法
  minimax(board, depth, alpha, beta, isMaximizing, role) {
    if (depth === 0) {
      return this.evaluate(board, role)
    }
    
    const moves = this.getValuableMoves(board, role)
    if (moves.length === 0) {
      return this.evaluate(board, role)
    }
    
    if (isMaximizing) {
      let maxEval = -Infinity
      for (const [i, j] of moves) {
        board[i][j] = role
        const evalResult = this.minimax(board, depth - 1, alpha, beta, false, role)
        board[i][j] = 0
        maxEval = Math.max(maxEval, evalResult)
        alpha = Math.max(alpha, evalResult)
        if (beta <= alpha) break
      }
      return maxEval
    } else {
      let minEval = Infinity
      for (const [i, j] of moves) {
        board[i][j] = role === 1 ? 2 : 1 // 对手的棋子
        const evalResult = this.minimax(board, depth - 1, alpha, beta, true, role)
        board[i][j] = 0
        minEval = Math.min(minEval, evalResult)
        beta = Math.min(beta, evalResult)
        if (beta <= alpha) break
      }
      return minEval
    }
  }

  // 搜索最佳移动
  search(board, depth = 4, player) {
    const moves = this.getValuableMoves(board, player)
    let bestMove = null
    let bestValue = -Infinity
    
    for (const [i, j] of moves) {
      board[i][j] = player
      const value = this.minimax(board, depth - 1, -Infinity, Infinity, false, player)
      board[i][j] = 0
      
      if (value > bestValue) {
        bestValue = value
        bestMove = [i, j]
      }
    }
    
    return {
      point: bestMove,
      value: bestValue
    }
  }

  // 获取随机移动（备用方案）
  getRandomMove(board) {
    const emptyPositions = []
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < this.size; j++) {
        if (board[i][j] === 0) {
          emptyPositions.push([i, j])
        }
      }
    }
    
    if (emptyPositions.length === 0) {
      return null
    }
    
    const randomIndex = Math.floor(Math.random() * emptyPositions.length)
    const [row, col] = emptyPositions[randomIndex]
    
    return { row, col }
  }

  // 兼容性方法
  getAIInfo() {
    return {
      difficulty: this.difficulty,
      maxDepth: this.getSearchDepth(),
      cacheSize: 0,
      timeLimit: 5000
    }
  }

  getPerformanceReport() {
    return {
      currentMove: {
        thinkingTime: 0,
        depth: this.getSearchDepth(),
        nodesEvaluated: 0,
        cacheHits: 0,
        cacheMisses: 0
      },
      overall: {
        totalMoves: 0,
        averageThinkingTime: 0,
        maxDepth: this.getSearchDepth(),
        totalNodesEvaluated: 0,
        cacheHitRate: 0
      }
    }
  }

  getPerformanceMonitor() {
    return {
      getPerformanceReport: () => this.getPerformanceReport()
    }
  }

  clearCache() {
    // 简单AI没有缓存
  }

  isTimeUp() {
    return false
  }
} 